﻿using AutoMapper.Internal.Mappers;
using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using ERP.ERPSystem.RBAC;
using ERP.ERPSystem.ProductionSystem;
using System.Collections.Generic;
using ERP.Team.RBAC;
using System;
using System.Linq;

namespace ERP.Web.Controllers.ProductionSystem
{
    public class ProductionDispatchMainController : Controller
    {
        /// <summary>
        /// 生产系统——生产派单
        /// </summary>
        private readonly IProductionDispatchMainServices _productionDispatchMainServices;

        public ProductionDispatchMainController(IProductionDispatchMainServices productionDispatchMainServices)
        {
            _productionDispatchMainServices = productionDispatchMainServices;
        }

        /// <summary>
        /// 添加生产派单视图
        /// </summary>
        /// <param name="parentWorkOrderCode">父级工单编号（可选）</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult AddDispatch(string parentWorkOrderCode = null)
        {
            ViewBag.ParentWorkOrderCode = parentWorkOrderCode;
            return View();
        }

        /// <summary>
        /// 添加生产派单
        /// </summary>
        /// <param name="productionDispatchMainDto"></param>
        /// <returns></returns>
        [HttpPost]
        [IgnoreAntiforgeryToken]
        public async Task<int> AddProductionDispatch(ProductionDispatchMainDto productionDispatchMainDto)
        {
            var i = await _productionDispatchMainServices.AddProductionDispatch(productionDispatchMainDto);
            return i;
        }

        /// <summary>
        /// 获取下一个工单编号（预览）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetNextWorkOrderCode()
        {
            try
            {
                var today = DateTime.UtcNow;
                var datePrefix = $"MO{today:yyyyMMdd}"; // 格式：MO20250120
                
                // 查询当天已有的工单数量
                var todayCount = await _productionDispatchMainServices.GetWorkOrderCountByPrefix(datePrefix);
                var nextNumber = todayCount + 1;
                
                // 生成4位序号，如：MO20250120001
                var workOrderCode = $"{datePrefix}{nextNumber:D4}";
                
                return Json(workOrderCode);
            }
            catch (Exception ex)
            {
                return Json($"MO{DateTime.UtcNow:yyyyMMdd}0001"); // 失败时返回默认编号
            }
        }

        /// <summary>
        /// 显示生产派单查询页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetDispatch()
        {
            return View();
        }

        /// <summary>
        /// 获取生产派单列表数据（增强查询）
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <param name="taskName">任务名称</param>
        /// <param name="workOrderCode">工单编号</param>
        /// <param name="workOrderName">工单名称</param>
        /// <param name="processName">工序名称</param>
        /// <param name="workGroupName">工作站名称</param>
        /// <param name="productMaterialName">产品物料名称</param>
        /// <param name="orderTarget">派单人</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDispatchList(
            int page = 1, 
            int limit = 10, 
            string taskName = "", 
            string workOrderCode = "", 
            string workOrderName = "", 
            string processName = "",
            string workGroupName = "",
            string productMaterialName = "",
            string orderTarget = "")
        {
            try
            {
                var allData = await _productionDispatchMainServices.GetProductionDispatch();
                
                // 增强的过滤逻辑
                var filteredData = allData.Where(x => 
                    // 基础查询条件
                    (string.IsNullOrEmpty(taskName) || (!string.IsNullOrEmpty(x.TaskName) && x.TaskName.Contains(taskName))) &&
                    (string.IsNullOrEmpty(workOrderCode) || (!string.IsNullOrEmpty(x.ProductionWorkOrderCode) && x.ProductionWorkOrderCode.Contains(workOrderCode))) &&
                    (string.IsNullOrEmpty(workOrderName) || (!string.IsNullOrEmpty(x.WorkOrderName) && x.WorkOrderName.Contains(workOrderName))) &&
                    (string.IsNullOrEmpty(processName) || x.DocumentStatus.ToString() == processName) &&
                    // 新增查询条件
                    (string.IsNullOrEmpty(workGroupName) || (!string.IsNullOrEmpty(x.WorkGroupName) && x.WorkGroupName.Contains(workGroupName))) &&
                    (string.IsNullOrEmpty(productMaterialName) || (!string.IsNullOrEmpty(x.ProductMaterialName) && x.ProductMaterialName.Contains(productMaterialName))) &&
                    (string.IsNullOrEmpty(orderTarget) || (!string.IsNullOrEmpty(x.OrderTarget) && x.OrderTarget.Contains(orderTarget)))
                ).OrderBy(x => x.ProductionWorkOrderCode).ThenBy(x => x.Id).ToList();

                // 分页
                var totalCount = filteredData.Count;
                var pagedData = filteredData.Skip((page - 1) * limit).Take(limit).ToList();

                var result = new
                {
                    code = 0,
                    msg = "",
                    count = totalCount,
                    data = pagedData
                };

                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    code = 1,
                    msg = "获取数据失败：" + ex.Message,
                    count = 0,
                    data = new List<object>()
                });
            }
        }



        /// <summary>
        /// 重新分配派单人员
        /// </summary>
        /// <param name="id">派单ID</param>
        /// <param name="newPerson">新的派单人员</param>
        /// <returns></returns>
        [HttpPost]
        [IgnoreAntiforgeryToken]
        public async Task<IActionResult> ReassignPerson(int id, string newPerson)
        {
            try
            {
                var result = await _productionDispatchMainServices.UpdateOrderTarget(id, newPerson);
                return Json(new { success = result > 0, message = result > 0 ? "重新分配成功" : "重新分配失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "操作失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 批量重新分配派单人员
        /// </summary>
        /// <param name="ids">派单ID列表（逗号分隔）</param>
        /// <param name="newPerson">新的派单人员</param>
        /// <returns></returns>
        [HttpPost]
        [IgnoreAntiforgeryToken]
        public async Task<IActionResult> BatchReassignPerson(string ids, string newPerson)
        {
            try
            {
                var idList = ids.Split(',').Select(int.Parse).ToList();
                var result = await _productionDispatchMainServices.BatchUpdateOrderTarget(idList, newPerson);
                return Json(new { success = result > 0, message = result > 0 ? "批量重新分配成功" : "批量重新分配失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "操作失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 显示修改生产派单页面
        /// </summary>
        /// <param name="id">派单ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> EditDispatch(int id)
        {
            try
            {
                var dispatch = await _productionDispatchMainServices.GetProductionDispatchById(id);
                if (dispatch == null)
                {
                    return NotFound("未找到指定的派单记录");
                }
                return View(dispatch);
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = "获取派单信息失败：" + ex.Message;
                return View();
            }
        }

        /// <summary>
        /// 更新生产派单
        /// </summary>
        /// <param name="id">派单ID</param>
        /// <param name="productionDispatchMainDto">更新的派单信息</param>
        /// <returns></returns>
        [HttpPost]
        [IgnoreAntiforgeryToken]
        public async Task<IActionResult> UpdateDispatch(int id, ProductionDispatchMainDto productionDispatchMainDto)
        {
            try
            {
                var result = await _productionDispatchMainServices.UpdateProductionDispatch(id, productionDispatchMainDto);
                return Json(new { success = result > 0, message = result > 0 ? "修改成功" : "修改失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "操作失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 批量编辑指派人
        /// </summary>
        /// <param name="ids">派单ID列表（逗号分隔）</param>
        /// <param name="assignee">指派人</param>
        /// <returns></returns>
        [HttpPost]
        [IgnoreAntiforgeryToken]
        public async Task<IActionResult> BatchUpdateAssignee(string ids, string assignee)
        {
            try
            {
                var idList = ids.Split(',').Select(int.Parse).ToList();
                var result = await _productionDispatchMainServices.BatchUpdateOrderTarget(idList, assignee);
                return Json(new { success = result > 0, message = result > 0 ? "批量编辑成功" : "批量编辑失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "操作失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除单条生产派单记录
        /// </summary>
        /// <param name="id">派单ID</param>
        /// <returns></returns>
        [HttpPost]
        [IgnoreAntiforgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                var result = await _productionDispatchMainServices.DeleteProductionDispatch(id);
                return Json(new { success = result > 0, message = result > 0 ? "删除成功" : "删除失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 批量删除生产派单记录
        /// </summary>
        /// <param name="ids">派单ID列表（逗号分隔）</param>
        /// <returns></returns>
        [HttpPost]
        [IgnoreAntiforgeryToken]
        public async Task<IActionResult> BatchDelete(string ids)
        {
            try
            {
                var idList = ids.Split(',').Select(int.Parse).ToList();
                var result = await _productionDispatchMainServices.BatchDeleteProductionDispatch(idList);
                return Json(new { success = result > 0, message = result > 0 ? "批量删除成功" : "批量删除失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "批量删除失败：" + ex.Message });
            }
        }


    }
}
